package com.gobygang.client.suggest;

import java.util.Collection;
import java.util.LinkedList;

import com.google.gwt.core.client.JsArray;
import com.google.gwt.maps.client.geocode.Geocoder;
import com.google.gwt.maps.client.geocode.LocationCallback;
import com.google.gwt.maps.client.geocode.Placemark;
import com.google.gwt.user.client.ui.SuggestOracle;


public class AddressOracle extends SuggestOracle {

    // this instance is needed, to call the getLocations-Service
    private static Geocoder geocoder;


    public AddressOracle() {
        //geocoder = new Geocoder();
    }
    
    static public void  setGeocoder(){
    	geocoder = new Geocoder();
    }

    @Override
    public void requestSuggestions(final Request request,
            final Callback callback) {
        // this is the string, the user has typed so far
        String addressQuery = request.getQuery();
        // look up for suggestions, only if at least 2 letters have been typed
        if (addressQuery.length() > 2 && geocoder != null) {    
            geocoder.getLocations(addressQuery, new LocationCallback() {

                @Override
                public void onFailure(int statusCode) {
                    // do nothing
                }

                @Override
                public void onSuccess(JsArray<Placemark> places) {
                    // create an oracle response from the places, found by the
                    // getLocations-Service
                    Collection<Suggestion> result = new LinkedList<Suggestion>();
                    for (int i = 0; i < places.length(); i++) {
                        String address = places.get(i).getAddress();
                        AddressSuggestion newSuggestion = new AddressSuggestion(
                                address);
                        result.add(newSuggestion);
                    }
                    Response response = new Response(result);
                    callback.onSuggestionsReady(request, response);
                }

            });

        } else {
            Response response = new Response();
            //Response response = new Response(Collections.<Suggestion> emptyList());
            callback.onSuggestionsReady(request, response);
        }

    }
}
